package com.sywb.chuangyebao.contract;

import android.annotation.SuppressLint;
import android.media.MediaPlayer;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.czt.mp3recorder.MP3Player;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.Column;
import com.sywb.chuangyebao.bean.Comment;
import com.sywb.chuangyebao.bean.Live;
import com.sywb.chuangyebao.bean.VideoDetail;
import com.sywb.chuangyebao.utils.DateTimeUtils;
import com.sywb.chuangyebao.utils.GlideUtils;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.view.dialog.ShareDialog;

import org.bining.footstone.log.Logger;
import org.bining.footstone.utils.TimeUtils;
import org.bining.footstone.utils.ToastUtils;

import java.util.Timer;
import java.util.TimerTask;

public interface TrainDetailContract {

    interface TrainDetailView extends SupportCommentDetailContract.View {

        void setVideoStart(String videoUrl, String videoLength);
    }

    class Presenter extends SupportCommentDetailContract.Presenter<TrainDetailView> implements android.view.View.OnClickListener {

        private boolean isCollected;
        private MP3Player mp3Player;

        private Column column;
        private VideoDetail videoDetail;

        @Override
        public void onStart() {
            super.onStart();
        }

        @Override
        public void initData() {
            super.initData();
            pageNumber = 1;
            onStartAsync();
            getCommentList();
            loadDetailFinish();
        }

        public void changeCommentCount(int postion, int count) {
            Comment comment = recyclerAdapter.getDatas().get(postion);
            comment.reply_count = count;
            recyclerAdapter.notifyDataSetChanged();
        }

        public void changeCommentThumb(int postion, boolean isThumb, int thumbCount) {
            Comment comment = recyclerAdapter.getDatas().get(postion);
            comment.is_thumb = isThumb;
            comment.thumb_count = thumbCount;
            recyclerAdapter.notifyDataSetChanged();
        }

        @Override
        public void onRecyclerItemClick(int i) {
        }

        @Override
        void changeFollow() {
            ToastUtils.show(mContext, "关注成功");
        }

        @Override
        void changeAgree() {

        }

        @Override
        void changeFavorite() {
            ToastUtils.show(mContext, isCollected ? "取消收藏" : "收藏成功");
            isCollected = !isCollected;
            mView.setIsFavorite(isCollected);
        }

        @Override
        void changeComment(boolean isAdd) {
        }

        public void favorite() {
            favorite(!isCollected);
        }

        public void showDialog() {
            int id;
            String title;
            String text;
            String image;
            String shareType;

            if (column != null) {
                shareType = Constants.TOPIC_TYPE_SPECIAL;
                id = column.column_id;
                title = column.title;
                text = column.des;
                image = column.thumb_pic;
            } else if (videoDetail != null) {
                shareType = seekBar == null ? Constants.TOPIC_TYPE_VIDEO_TRAIN : Constants.TOPIC_TYPE_AUDIO_TRAIN;
                id = videoDetail.video_id;
                title = videoDetail.title;
                text = videoDetail.description;
                image = videoDetail.media_logo;
            } else {
                showMessage("获取分享信息失败");
                return;
            }

            ShareDialog sharedDialog = ShareDialog.newInstance(shareType, id, ShareDialog.TYPE_REPORT, title, text, image);
            sharedDialog.show(mView.getMyFragmentManager(), "Shared");
        }

        public void initLiveView(Live live) {
            android.view.View headView = mActivity.getLayoutInflater().inflate(R.layout.layout_train_video_detail, null);
            headView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            recyclerAdapter.setHeaderView(headView);

            tvVideoName = headView.findViewById(R.id.tv_video_name);
            textView = headView.findViewById(R.id.richTextView);
            tvVideoName.setText(live.title);
            textView.setText(live.des);

            topicType = Constants.TOPIC_TYPE_VIDEO;
            topicId = live.live_id;
            initData();
        }

        public void initVideoView(int media_id) {
            android.view.View headView = mActivity.getLayoutInflater().inflate(R.layout.layout_train_video_detail, null);
            headView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            recyclerAdapter.setHeaderView(headView);

            tvVideoName = headView.findViewById(R.id.tv_video_name);
            textView = headView.findViewById(R.id.richTextView);
            getMediaDetail(0, media_id);
            topicType = Constants.TOPIC_TYPE_VIDEO;
            topicId = media_id;
            initData();
        }

        private ImageView ivPlay;
        private SeekBar seekBar;
        private TextView tvAudioTimeCurrent;
        private TextView tvAudioTimeTotal;
        private boolean isChanging = false;//互斥变量，防止定时器与SeekBar拖动时进度冲突

        public void initAudioView(int media_id) {
            android.view.View headView = mActivity.getLayoutInflater().inflate(R.layout.layout_train_audio_detail, null);
            headView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            recyclerAdapter.setHeaderView(headView);

            ivAudio = headView.findViewById(R.id.iv_audio);
            tvVideoName = headView.findViewById(R.id.tv_video_name);
            textView = headView.findViewById(R.id.richTextView);
            seekBar = headView.findViewById(R.id.seekbar);
            tvAudioTimeCurrent = headView.findViewById(R.id.tv_audio_time_current);
            tvAudioTimeTotal = headView.findViewById(R.id.tv_audio_time_total);
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                    tvAudioTimeCurrent.setText(DateTimeUtils.getMediaTimeNumber(seekBar.getProgress() / 1000));
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                    isChanging = true;
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                    boolean isFirst = initMp3Player();
                    if (isFirst) {
                        mp3Player.prepare(videoDetail.media_url, null);
                        seekBar.setMax(mp3Player.getMediaPlayer().getDuration());//设置进度条
                        Logger.e("duration:" + mp3Player.getMediaPlayer().getDuration());
                        tvAudioTimeTotal.setText(DateTimeUtils.getMediaTimeNumber(seekBar.getMax() / 1000));
                    }
                    mp3Player.getMediaPlayer().seekTo(seekBar.getProgress());
                    initTimer();
                    mp3Player.restart();
                    ivPlay.setImageResource(R.drawable.stop_br);
                }
            });

            ivPlay = headView.findViewById(R.id.iv_play);
            ivPlay.setOnClickListener(this);

            getMediaDetail(1, media_id);
            topicType = Constants.TOPIC_TYPE_AUDIO;
            topicId = media_id;
            initData();

        }

        private void getMediaDetail(final int mediaType, int media_id) {
            HttpUtils.getVideoDetail(media_id, new HttpCallback<VideoDetail>() {

                @Override
                public void onStart() {
                    super.onStart();
                    onStartAsync();
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }

                @Override
                public void onSuccess(VideoDetail model) {
                    if (model == null) {
                        return;
                    }

                    videoDetail = model;
                    isCollected = model.is_favorite;
                    mView.setIsFavorite(isCollected);
                    tvVideoName.setText(model.title);
                    textView.setText(model.description);

                    switch (mediaType) {
                        case 0:
                            //视频
                            mView.setVideoStart(model.media_url, model.media_length);
                            break;
                        case 1:
                            //音频
                            GlideUtils.getNormalIamgeToUrl(mActivity, model.media_logo, ivAudio);
                            tvAudioTimeTotal.setText(model.media_length);
                            break;
                    }
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                }
            });
        }

        @Override
        public void isNoData() {
            if (recyclerAdapter == null || mView == null) {
                return;
            }
            super.isNoData();
            mView.changeCommentCount(recyclerAdapter.getDataCount());
        }

        private ImageView ivAudio;
        private TextView tvVideoName;
        private LinearLayout llSpecialPerson;
        private ImageView ivSpecialPerson;
        private TextView tvSpecialPerson;
        private TextView tvSpecialTime;
        //        private TextView richTextView;
        private TextView textView;
        private WebView commonWebview;

        public void initSpecialView(int column_id) {
            android.view.View headView = mActivity.getLayoutInflater().inflate(R.layout.layout_train_special_detail, null);
            ivAudio = headView.findViewById(R.id.iv_audio);
            tvVideoName = headView.findViewById(R.id.tv_video_name);
            llSpecialPerson = headView.findViewById(R.id.ll_special_person);
            ivSpecialPerson = headView.findViewById(R.id.iv_special_person);
            tvSpecialPerson = headView.findViewById(R.id.tv_special_person);
            tvSpecialTime = headView.findViewById(R.id.tv_special_time);
//            richTextView = headView.findViewById(R.id.richTextView);
            commonWebview = headView.findViewById(R.id.common_webview);

            headView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            recyclerAdapter.setHeaderView(headView);
            initWebView();

            topicType = Constants.TOPIC_TYPE_SPECIAL;
            topicId = column_id;
            initData();

            HttpUtils.getColumn(column_id, new HttpCallback<Column>() {

                @Override
                public void onStart() {
                    super.onStart();
                    onStartAsync();
                }

                @Override
                public void onSuccess(Column model) {
                    if (model == null) {
                        return;
                    }

                    column = model;
                    isCollected = model.is_favorite;
                    mView.setIsFavorite(isCollected);
                    GlideUtils.getNormalIamgeToUrl(mActivity, model.thumb_pic, ivAudio);
                    tvVideoName.setText(model.title);

                    tvSpecialPerson.setText(model.author);
                    tvSpecialTime.setText(TimeUtils.ymd(model.update_time * 1000L));

//                    if (model.owner != null) {
//                        llSpecialPerson.setVisibility(View.VISIBLE);
//
//                        if (TextUtils.isEmpty(model.owner.getShowAvatar())) {
//                            ivSpecialPerson.setVisibility(View.GONE);
//                        } else {
//                            ivSpecialPerson.setVisibility(View.VISIBLE);
//                            GlideUtils.getCircleImageToUrl(mActivity, model.owner.getShowAvatar(), ivSpecialPerson, R.drawable.head_image);
//                        }
//
//                        tvSpecialPerson.setText(model.owner.getShowName());
//                        tvSpecialTime.setText(TimeUtils.ymd(model.update_time * 1000L));
//                    } else {
//                        llSpecialPerson.setVisibility(View.GONE);
//                    }

                    //设置文本 1=html片段，2=h5页面链接
                    switch (model.content_type) {
                        case 1:
//                            richTextView.setVisibility(View.GONE);

                            setHtml(model.content);
                            break;
                        case 2:
//                            commonWebview.setVisibility(View.GONE);
//                            richTextView.setText(model.content);
                            setURL(model.content);
                            break;
                    }
                }

                @Override
                public void onError(String strMsg) {
                    super.onError(strMsg);
                    showMessage(strMsg);
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    onFinishAsync();
                }
            });
        }

        /**
         * 初始化WebView
         */
        @SuppressLint("SetJavaScriptEnabled")
        private void initWebView() {
            /**
             * setAllowFileAccess 启用或禁止WebView访问文件数据 setBlockNetworkImage 是否显示网络图像
             * setBuiltInZoomControls 设置是否支持缩放 setCacheMode 设置缓冲的模式
             * setDefaultFontSize 设置默认的字体大小 setDefaultTextEncodingName 设置在解码时使用的默认编码
             * setFixedFontFamily 设置固定使用的字体 setJavaSciptEnabled 设置是否支持Javascript
             * setLayoutAlgorithm 设置布局方式 setLightTouchEnabled 设置用鼠标激活被选项
             * setSupportZoom 设置是否支持变焦
             * */
            WebSettings settings = commonWebview.getSettings();
            settings.setJavaScriptEnabled(true);// 设置支持javascript脚本
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            // 1.NARROW_COLUMNS：可能的话使所有列的宽度不超过屏幕宽度；2.NORMAL：正常显示不做任何渲染；3.SINGLE_COLUMN：把所有内容放大webview等宽的一列中
            // settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);// 排版适应屏幕
            settings.setDisplayZoomControls(false);
            settings.setAllowFileAccess(true); // 启用或禁止WebView访问文件数据
            settings.setBuiltInZoomControls(false); //  隐藏缩放按钮
            settings.setSupportZoom(true); // 支持缩放
            // settings.setUseWideViewPort(true);// 可任意比例缩放
            settings.setLoadWithOverviewMode(true);//setUseWideViewPort方法设置webview推荐使用的窗口；设置webview加载的页面的模式
            settings.setGeolocationEnabled(true);// 启用地理定位
            settings.setDomStorageEnabled(true);
            settings.setSaveFormData(true);// 保存表单数据
            // settings.setSavePassword(true);
            // settings.setTextZoom(200);
            // settings.setMixedContentMode(1);
            // settings.setAcceptThirdPartyCookies();
            commonWebview.setWebChromeClient(new WebChromeClient());
            commonWebview.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return false;
                }
            });
        }

        private void setURL(String url) {
            commonWebview.loadUrl(url);
        }

        /**
         * 设置需展示的Html片段
         */
        private void setHtml(String protocol) {
            if (protocol != null) {
                commonWebview.getSettings().setDefaultTextEncodingName("utf-8");
                commonWebview.loadDataWithBaseURL(null, protocol, "text/html", "UTF-8", null);
            } else {
                showMessage("未获取到内容,请稍后重试!");
            }
        }

        private Timer mTimer;
        private TimerTask mTimerTask;

        @Override
        public void onClick(android.view.View view) {
            switch (view.getId()) {
                case R.id.iv_play:
                    if (initMp3Player()) {
                        mp3Player.startPlay(videoDetail.media_url, null);
                        if (mp3Player.getMediaPlayer() == null) {
                            return;
                        }

                        seekBar.setMax(mp3Player.getMediaPlayer().getDuration());//设置进度条
                        Logger.e("duration:" + mp3Player.getMediaPlayer().getDuration());
                        tvAudioTimeTotal.setText(DateTimeUtils.getMediaTimeNumber(seekBar.getMax() / 1000));
                        initTimer();
                        return;
                    }
                    playOrPause();
                    break;
            }
        }

        private void playOrPause() {
            if (mp3Player.isPlaying()) {
                mp3Player.pausePlay();
                ivPlay.setImageResource(R.drawable.play_br);
                isChanging = true;
                mTimer.cancel();
            } else {
                mp3Player.restart();
                initTimer();
                ivPlay.setImageResource(R.drawable.stop_br);
            }
        }

        private boolean initMp3Player() {
            if (mp3Player == null) {
                mp3Player = MP3Player.getInstance();
                mp3Player.setOnMP3PlayerListener(new MP3Player.OnMP3PlayerListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        Logger.e("MediaPlayer onCompletion");
//                                setRecordViewStart(false);
                        seekBar.setProgress(0);
                        ivPlay.setImageResource(R.drawable.play_br);
                        tvAudioTimeCurrent.setText("00:00");
                        isChanging = true;
                        mTimer.cancel();
                    }

                    @Override
                    public void onSeekComplete(MediaPlayer mediaPlayer) {
                        Logger.e("MediaPlayer onSeekComplete");
                    }

                    @Override
                    public void onError(MediaPlayer mediaPlayer) {
                        onCompletion(mediaPlayer);
                        showMessage("播放错误,请稍候再试");
                    }
                });
                if (videoDetail == null) {
                    videoDetail = new VideoDetail();
                }
//                videoDetail.media_url = "/storage/emulated/0/Android/data/com.sywb.chuangyebao/files/voice/VIC_1517896915518183.mp3";
                ivPlay.setImageResource(R.drawable.stop_br);
                return true;
            }
            return false;
        }


        private void initTimer() {
            //----------定时器记录播放进度---------//
            isChanging = false;
            mTimer = new Timer();
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    if (isChanging) {
                        return;
                    }

                    try {
//                        if (seekBar.getProgress() > 0 && mp3Player.getMediaPlayer().getCurrentPosition() == seekBar.getProgress()) {
//                            isChanging = true;
//                            return;
//                        }

                        if (mp3Player.getMediaPlayer() == null) {
                            return;
                        }
                        seekBar.setProgress(mp3Player.getMediaPlayer().getCurrentPosition());
                        Logger.e("currentPosition:" + mp3Player.getMediaPlayer().getCurrentPosition() + "seekBar:" + seekBar.getProgress());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            mTimer.schedule(mTimerTask, 0, 10);
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            if (mp3Player != null) {
                mp3Player.stopPlay();
            }
            if (mTimer != null) {
                isChanging = true;
                mTimer.cancel();
                Logger.e("onDestroy");
            }
        }
    }
}

